package org.logsin37.util.press.entity

import org.apache.groovy.json.internal.LazyMap
import org.springframework.http.RequestEntity

import java.util.stream.Collectors
import java.util.stream.Stream

class TestReport {

    RequestEntity<?> requestEntity
    int concurrentCount
    long seconds
    int totalCount
    double successRate
    double avgResponseTime
    List<LazyMap> details

    static TestReport generateReport(RequestEntity<?> requestEntity, int concurrentCount, long seconds, List<TraceLog>[] traceLogArray) {
        def report = new TestReport()
        report.requestEntity = requestEntity
        report.concurrentCount = concurrentCount
        report.seconds = seconds
        report.details = new ArrayList<>()

        def traceLogs = Stream.of(traceLogArray).flatMap({it.stream()}).filter({it.endTimeStamp != null}).collect(Collectors.toList())
        report.totalCount = traceLogs.size()
        if(report.totalCount != 0) {
            report.successRate = traceLogs.stream().filter({it.success}).count() * 100 / report.totalCount
            report.avgResponseTime = traceLogs.stream().mapToLong({it.titleTime}).average().orElse(0d)
            Map<String, List<TraceLog>> map = traceLogs.stream().collect(Collectors.groupingBy(it -> it.endTimeStamp.toString()))
            map.entrySet().stream().sorted((A, B) -> A.key.compareTo(B.key))
            .forEach({
                def o = new LazyMap()
                def l = it.value
                if(l == null) {
                    return
                }
                o.time = it.key
                o.totalCount = l.size()
                o.successRate = l.stream().filter({it.success}).count() * 100 / o.totalCount
                o.avgResponseTime = l.stream().mapToLong({it.titleTime}).average().orElse(0d)
                report.details.add o
            })
        }

        report
    }

}
